<!-- 职位体系管理左侧组件 -->

<template>
  <div class="left-list">
    <div @click="collapse" class="collapseBtn">
      <IconCaretRight v-if="isCollapsed" />
      <IconCaretLeft v-else />
    </div>
    <a-layout class="layout-demo">
      <a-layout-sider
        collapsible
        breakpoint="xl"
        hide-trigger
        :collapsed="isCollapsed"
        :collapsed-width="0"
      >
        <div v-show="!isCollapsed">
          <div class="header">
            <span class="title">职位类别</span>
            <a-tooltip content="点击前往职位类别设置">
              <a-button
                @click="goSetting"
                :style="{
                  positon: 'relative',
                  top: '50%',
                  transform: 'translateY(-50%)'
                }"
                type="text"
                >设置</a-button
              >
            </a-tooltip>
          </div>
          <a-scrollbar style="height: 600px; overflow: auto">
            <div class="scroll">
              <a-input-search
                allow-clear
                class="search"
                placeholder="输入分类名称"
                v-model="searchVal"
                @change="changeVal"
              />
              <div class="scroll-content">
                <a-tree
                  :fieldNames="{
                    key: 'id',
                    title: 'C7341027925C943708F3AEF98703ECC47'
                  }"
                  :data="treeData"
                  v-model:expanded-keys="expandKey"
                  showLine
                  @select="selectTree"
                  v-model:selected-keys="selectedKey"
                >
                  <template #switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #title="nodeData">
                    <template
                      v-if="((index = getMatchIndex(nodeData.name)), index < 0)"
                      >{{ nodeData.name }}</template
                    >
                    <span v-else>
                      {{ nodeData.name?.substr(0, index) }}
                      <span style="color: var(--color-primary-light-4)">
                        {{
                          nodeData.name?.substr(index, searchVal.length)
                        }} </span
                      >{{ nodeData.name?.substr(index + searchVal.length) }}
                    </span>
                  </template>
                </a-tree>
              </div>
            </div>
          </a-scrollbar>
        </div>
      </a-layout-sider>
    </a-layout>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue';
import { flatTree } from '@/utils/utils';
import { GetPositionTypeList } from '@/apis/management/organization/baseSetting';
import mitter from '@/utils/mitt';

const router = useRouter();

let searchVal = ref(''); // 搜索框
let originTreeData = ref([]); // 储存最初的树形数据
let expandKey: any = ref([]); // 储存当前搜索要展开的选项
let selectedKey = ref<number[]>([]); // 选中的值

// 搜索值
const searchData = (keyword: string) => {
  const loop = (data: any) => {
    const result: any = [];
    data.forEach((item: any) => {
      if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
          expandKey.value.push(item.id);
        }
      }
    });
    return result;
  };

  return loop(originTreeData.value);
};

/* 储存实时的属性数据 */
const treeData = computed(() => {
  if (!searchVal.value) return originTreeData.value;
  return searchData(searchVal.value);
});

const dataTreeFilter = (treeData: any) => {
  const data = treeData.map((item: any, index1: any) => ({
    ...item,
    // ...controldataTreeFilter(item.controlData),
    children:
      item.children && item.children.length
        ? dataTreeFilter(item.children)
        : null
  }));
  return data;
};

// 搜索框值
const changeVal = (val: string) => {
  mitter.emit('positionTreeSelect', val);
};

let flatData = ref<any>([]); // 储存扁平化的数据
// 获取列表数据
const getData = async () => {
  try {
    const { positionCategoryList } = await GetPositionTypeList();
    flatData.value = flatTree(positionCategoryList);
    originTreeData.value = dataTreeFilter(positionCategoryList);
    // // 默认展开所有行
    flatData.value.forEach((item: any) => {
      expandKey.value.push(item.id);
    });
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let isCollapsed = ref(false); // 判断是否收起
const collapse = (collapsed: boolean) => {
  isCollapsed.value = !isCollapsed.value;
};

// 获取符合的数据
const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

// 点击导航栏跳往对应详情
const selectTree = (selectedKeys: number, data: any) => {
  console.log(data);
  selectedKey.value = selectedKeys;
  mitter.emit('positionTreeSelect', data.node.name);
};

watchEffect(() => {
  // 重置侧边栏数据
  mitter.on('resetPositionTree', (res: any) => {
    selectedKey.value = [];
  });
});

const goSetting = () => {
  router.push({
    name: 'PositionSort'
  });
};
</script>

<style scoped lang="less">
.left-list {
  position: relative;
  padding: 0 15px;
  .collapseBtn {
    position: absolute;
    z-index: 999;
    top: 40%;
    right: 15px;
    height: 70px;
    width: 15px;
    background-color: #eee;
    line-height: 70px;
    text-align: center;
    cursor: pointer;
  }
  .layout-demo {
    height: 100%;
  }
  .header {
    display: flex;
    justify-content: space-between;
    height: 60px;

    .title {
      line-height: 60px;
      // position: relative;
      // right: 55px;
    }
    .title::before {
      position: relative;
      top: 5px;
      left: 10px;
      display: inline-block;
      height: 20px;
      width: 5px;
      margin-right: 20px;
      border-radius: 2px;
      // transform: translateY(-50%);
      content: '';
      background-color: #165dff;
    }
  }

  // height: 300px;
  .scroll {
    padding: 10px;
    .search {
      background-color: #fff;
      height: 40px;
      border: 1px solid #ccc;
    }
  }
}
</style>
